<script setup>
import { ref, onMounted, nextTick, getCurrentInstance } from 'vue';
import { ElButton, ElCard, ElPagination, ElDialog, ElInput } from 'element-plus';
import { Edit } from '@element-plus/icons-vue'
import { useRouter,useRoute } from 'vue-router';
import { solutionSelectService } from '@/api/solution'
import { inject } from 'vue';
import { solutionAddService,solutionModifyService, solutionDeleteService } from '@/api/solution';
import { useAdminStore } from '@/store/admin';
import { userSelectService } from '@/api/user'
import { adminGetService } from '@/api/admin'
import { MdPreview } from 'md-editor-v3';

const adminStore = useAdminStore()

const instance = getCurrentInstance();  // 获取当前实例
const $imageUrlPre = instance.appContext.config.globalProperties.$imageUrlPre;


// 响应式数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(5); // 每页显示条数
const totalSolutions = ref(0); // 总题解数
const solutions = ref([]); // 题解列表
const dialogVisible = ref(false); // 模态框显示状态
const newSolution = ref({
  title: '',
  content: ''
}); // 新题解的内容

// 模拟的题解数据
const allSolutions = [
  { id: 1, avatar: 'https://www.example.com/avatar1.jpg', userName: '小明', title: '题解 1', content: '这是一个示例题解内容。', likes: 10 },
  { id: 2, avatar: 'https://www.example.com/avatar2.jpg', userName: '小红', title: '题解 2', content: '这是另一个示例题解内容。', likes: 20 },
  { id: 3, avatar: 'https://www.example.com/avatar3.jpg', userName: '小刚', title: '题解 3', content: '这是第三个示例题解内容。', likes: 30 },
  { id: 4, avatar: 'https://www.example.com/avatar4.jpg', userName: '小李', title: '题解 4', content: '这是第四个示例题解内容。', likes: 40 },
  { id: 5, avatar: 'https://www.example.com/avatar5.jpg', userName: '小张', title: '题解 5', content: '这是第五个示例题解内容。', likes: 50 },
  { id: 6, avatar: 'https://www.example.com/avatar6.jpg', userName: '小王', title: '题解 6', content: '这是第六个示例题解内容。', likes: 60 },
  { id: 7, avatar: 'https://www.example.com/avatar7.jpg', userName: '小赵', title: '题解 7', content: '这是第七个示例题解内容。', likes: 70 },
  { id: 8, avatar: 'https://www.example.com/avatar8.jpg', userName: '小刘', title: '题解 8', content: '这是第八个示例题解内容。', likes: 80 },
];


const titleId = ref()
const route = useRoute()
// titleId.value = inject('titleId')
// console.log(titleId.value)
const props = defineProps({
  currentTitleId: Number,
  currentTitleName: Number,
});

// const currentTitleId = route.query.titleId
// const currentTitleName = route.query.titleName
console.log('id = ' + props.currentTitleId)
console.log('titleName = ' + props.currentTitleName)

const fetchSolutions = async () => {
  titleId.value = props.currentTitleId
  console.log(titleId.value)

  //根据题目id获取题解数据
  const res = await solutionSelectService(currentPage.value, pageSize.value, titleId.value)
  if (res.data.status === 'success') {
    solutions.value = res.data.data.list
    totalSolutions.value = res.data.data.totalCount
  }
  const start = (currentPage.value - 1) * pageSize.value;
  const end = currentPage.value * pageSize.value;

  // 使用 Promise.all 并行查询每个 solution 的用户信息
  const userPromises = solutions.value.map(async (solution) => {
    //根据userId查询admin信息
    const roleRes = await adminGetService(solution.userId)
    const admin = ref()
    if (roleRes.data.status === 'success') {
      admin.value = roleRes.data.data
    }
    if (admin.value.role == 3) {
      const res1 = await userSelectService(admin.value.account);  // 查询用户信息
      if (res1.data.status === 'success') {

        solution.avatar = $imageUrlPre + res1.data.data.avatar;  // 将头像赋值到 solution 中
      }
    } else {//使用默认的管理员头像
      solution.avatar = '/src/assets/image/avatar/manager.png'
      solution.userName += "(管理员)"
    }
  });

  // 等待所有查询完成
  await Promise.all(userPromises);

  // const currentSolutions = allSolutions.slice(start, end);
  console.log(solutions.value)

  // solutions.value = currentSolutions;
  // totalSolutions.value = allSolutions.length;
};

// 模拟点赞操作
const likeSolution = (solution) => {
  solution.likes += 1;
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchSolutions();
};


// 页面加载时获取数据
onMounted(async () => {
  await fetchSolutions();
});

const updateShowSolution = inject('update-show')

// 返回按钮逻辑
const goBack = () => {
  updateShowSolution(false)
};

// 跳转到题解详情页面
const router = useRouter();
const goToSolution = (e,solutionId) => {
  // 如果点击的是按钮，则不执行 goToSolution
  if (e.target.closest('.solution-button')) {
    return;
  }
  router.push({ path: '/solutionInfo', query: { solutionId,titleName: props.currentTitleName } });
};

// 打开写题解模态框
const openCreateSolutionDialog = () => {
  dialogVisible.value = true;
};

// 发布新题解
const publishSolution = () => {
  // 模拟发布逻辑
  allSolutions.push({
    id: allSolutions.length + 1,
    avatar: 'https://www.example.com/avatar-default.jpg',
    userName: '新用户',
    title: newSolution.value.title,
    content: newSolution.value.content,
    likes: 0,
  });

  // 关闭模态框并清空输入内容
  dialogVisible.value = false;
  newSolution.value = { title: '', content: '' };
  fetchSolutions();
};

// 清空编辑器内容
const clearEditor = () => {
  newSolution.value = { title: '', content: '' };
};

/**
 * 写题解
 */
const solutionModel = ref(false)
const solution = ref({
  titleId: '',
  solutionContent: '',
  userId: ''
})
const openSolutionModal = () => {
  solutionModel.value = true
  solution.value.titleId = titleId.value
  solution.value.userId = adminStore.admin.userId
}
//发送请求
const submitSolution = async () => {
  const res = await solutionAddService(solution.value)
  if (res.data.status === 'success') {
    ElMessage.success('发布题解成功')
    fetchSolutions()
  } else {
    ElMessage.error(res.data.info)
  }
  solutionModel.value = false
}

/**
 * 修改题解
 */
 const solutionModifyModel = ref(false)
 const solutionModify = ref({
  solutionId: '',
  titleId: '',
  solutionContent: '',
  userId: ''
})
 const openModifySolutionModal = (solution) => {
  solutionModifyModel.value = true
  solutionModify.value.solutionId = solution.solutionId
  solutionModify.value.solutionContent = solution.solutionContent
  solutionModify.value.titleId = titleId.value
  solutionModify.value.userId = solution.userId
  console.log(solutionModify.value)
}
const updateSolution = async(solutionId) => {
  const res = await solutionModifyService(solutionModify.value)
  if(res.data.status === 'success'){
    ElMessage.success('修改成功')
    fetchSolutions()
    solutionModifyModel.value = false
  }else{
    ElMessage.error(res.data.info)
  }
}

/**
 * 删除题解
 */
const deleteSolution = async (solutionId) => {
  ElMessageBox.confirm(
    '确定要删除该题解吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await solutionDeleteService(solutionId)
      if (res.data.status === 'success') {
        ElMessage.success('删除成功')
        fetchSolutions()
      } else {
        ElMessage.error(res.data.info)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
</script>

<template>
  <!-- 填写题解内容模态窗口 -->
  <el-dialog v-model="solutionModel" fullscreen top="40vh" width="70%" draggable>
    <span>题解内容</span>
    <template #footer>
      <div>
        <v-md-editor v-model="solution.solutionContent" height="400px" :include-level="[1, 2, 3, 4]"
          :disabled-menus="[]" @upload-image="handleUploadImage" />
      </div>
      <div class="dialog-footer">
        <el-button @click="solutionModel = false">取消</el-button>
        <el-button type="primary" @click="submitSolution">
          发布
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改题解模态窗口 -->
  <el-dialog v-model="solutionModifyModel" fullscreen top="40vh" width="70%" draggable>
    <span>题解内容</span>
    <template #footer>
      <div>
        <v-md-editor v-model="solutionModify.solutionContent" height="400px" :include-level="[1, 2, 3, 4]"
          :disabled-menus="[]" @upload-image="handleUploadImage" />
      </div>
      <div class="dialog-footer">
        <el-button @click="solutionModifyModel = false">取消</el-button>
        <el-button type="primary" @click="updateSolution">
          修改
        </el-button>
      </div>
    </template>
  </el-dialog>
  <div class="page-container">
    <!-- 左侧装饰栏 -->
    <div class="left-decor"></div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 返回按钮 -->
      <div class="back-btn">
        <el-button type="text" icon="el-icon-arrow-left" @click="goBack">←返回</el-button>
      </div>

      <!-- 写题解按钮 -->
      <div class="create-solution-btn">
        <el-button type="primary" @click="openSolutionModal">
          <el-icon>
            <Edit />
          </el-icon> 写题解
        </el-button>
        <span class="solution-stats">{{ props.currentTitleName }}的题解：共{{ totalSolutions }}条</span>
      </div>

      <!-- 题解列表 -->
      <div class="solutions-list">
        <el-card v-for="(solution, index) in solutions" :key="index" class="solution-item"
          @click="goToSolution($event, solution.solutionId)">
          <div class="solution-header">
            <img class="avatar" :src="solution.avatar" alt="user avatar" />
            <div class="user-info">
              <div class="user-name">{{ solution.userName }}</div>
              <!-- <div class="solution-title">{{ solution.title }}</div> -->
            </div>
          </div>
          <MdPreview class="solution-body" style="background: white" :modelValue="solution.solutionContent">
          </MdPreview>
          <!-- <div class="solution-body">
              <p>{{ solution.solutionContent }}</p>
            </div> -->
          <div class="solution-button">
            <el-button type="info" @click="openModifySolutionModal(solution)">修改</el-button>
            <el-button type="danger" @click="deleteSolution(solution.solutionId)">删除</el-button>
          </div>
          <div class="solution-footer">
            <el-button icon="el-icon-thumb" size="mini" @click.stop="likeSolution(solution)">点赞 ({{ solution.likes
            }})</el-button>
          </div>
        </el-card>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="totalSolutions"
          layout="prev, pager, next" @current-change="handlePageChange"></el-pagination>
      </div>


    </div>

    <!-- 右侧装饰栏 -->
    <div class="right-decor"></div>
  </div>
</template>

<style scoped>
.page-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px;
}

.left-decor,
.right-decor {
  flex: 1;
  background: #f0f0f0;
  min-height: 100vh;
}

.main-content {
  flex: 3;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.back-btn {
  margin-bottom: 20px;
}

.create-solution-btn {
  margin-bottom: 20px;
  .solution-stats {
    margin-left: 10%;
    font-size: 14px;
    color: #0a0aed; /* 蓝色文字 */
    background: linear-gradient(135deg, #6D9DC5, #A7BFD9); /* 渐变背景 */
    padding: 5px 10px;
    border-radius: 20px; /* 圆角 */
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
    font-weight: 500;
    transition: transform 0.3s ease, background 0.3s ease;
  }
}

.solutions-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.solution-item {
  width: 100%;
  cursor: pointer;
}

.solution-item:hover {
  background-color: #f5f5f5;
}

.solution-header {
  display: flex;
  gap: 10px;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: bold;
}

.solution-title {
  font-size: 14px;
  color: #999;
}

.solution-body {
  margin-top: 10px;
}

.solution-body :deep() p {
  display: -webkit-box;
  /* 使用弹性盒子模型 */
  -webkit-box-orient: vertical;
  /* 让内容垂直排列 */
  -webkit-line-clamp: 2;
  /* 限制为2行 */
  overflow: hidden;
  /* 隐藏溢出的文本 */
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */
  line-height: 1.5;
  /* 设置行高 */
}

.solution-button {
  float: left;
  margin-top: 2%;
}

.solution-footer {
  margin-top: 15px;
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>